package com.hanlink.dsp.ca.ui.fragment;

import android.os.Bundle;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.edge.pbx.utils.StringUtils;
import com.edge.pbx.view.PbxCircleRadioSeekBar;
import com.edge.pbx.view.PbxCircleSeekBar;
import com.edge.pbx.view.common.VerticalSeekBar;

import com.edge.pbxdsp.R;
import com.hanlink.dsp.ca.model.channel.LevelChannel;
import com.hanlink.dsp.ca.ui.base.BaseAppFragment;
import com.hanlink.dsp.util.BLog;
import com.hanlink.dsp.util.Constants;
import com.hanlink.dsp.util.DataUtil;
import com.hanlink.dsp.util.ViewUtil;
import com.qztech.utils.YzDebug;

import java.util.ArrayList;
import java.util.List;

//import butterknife.BindView;
//import butterknife.BindViews;
//import butterknife.OnClick;

import static com.hanlink.dsp.DspSettings.ADVANCE_SETTINGS;
import static com.hanlink.dsp.util.Constants.DIENABLED_ALPHA;

public class GainFragment extends BaseAppFragment {

//    @BindViews({R.id.cbBtnCh1, R.id.cbBtnCh2, R.id.cbBtnCh3, R.id.cbBtnCh4, R.id.cbBtnCh5, R.id.cbBtnCh6, R.id.cbBtnCh7, R.id.cbBtnCh8})
//    CheckBox[] cbxChannels;//Leve CH


//    @BindViews({R.id.eqc_1, R.id.eqc_2, R.id.eqc_3, R.id.eqc_4, R.id.eqc_5, R.id.eqc_6, R.id.eqc_7, R.id.eqc_8})
//    AdvanceChannel[] mEqChannel;
//    @BindViews({R.id.link1, R.id.link2, R.id.link3, R.id.link4, R.id.link5, R.id.link6, R.id.link7, R.id.link8})
//    CheckBox[] mLinks;

    private ImageButton gain_btn_linked_1,gain_btn_linked_2,gain_btn_linked_3,gain_btn_linked_4,gain_btn_linked_5,gain_btn_linked_6,gain_btn_linked_7,gain_btn_linked_8;
   // @BindViews({R.id.gain_btn_linked_1,R.id.gain_btn_linked_2,R.id.gain_btn_linked_3,R.id.gain_btn_linked_4,R.id.gain_btn_linked_5,R.id.gain_btn_linked_6,R.id.gain_btn_linked_7,R.id.gain_btn_linked_8})
    ImageButton[] mIvLinks;

    private ImageButton gain_btn_degress_1,gain_btn_degress_2,gain_btn_degress_3,gain_btn_degress_4,gain_btn_degress_5,gain_btn_degress_6,gain_btn_degress_7,gain_btn_degress_8;
    //@BindViews({R.id.gain_btn_degress_1,R.id.gain_btn_degress_2,R.id.gain_btn_degress_3,R.id.gain_btn_degress_4,R.id.gain_btn_degress_5,R.id.gain_btn_degress_6,R.id.gain_btn_degress_7,R.id.gain_btn_degress_8})
    ImageButton mChDegress[];

   // @BindView(R.id.gain_seekbar_total_vol)
    VerticalSeekBar sbTotalVol;//总音量

    //@BindView(R.id.pbx_gain_btn_total_mute)
    Button mCbxMute;


    //========
    private ImageButton gain_btn_mute_1,gain_btn_mute_2,gain_btn_mute_3,gain_btn_mute_4,gain_btn_mute_5,gain_btn_mute_6,gain_btn_mute_7,gain_btn_mute_8;
    //@BindViews({R.id.gain_btn_mute_1,R.id.gain_btn_mute_2,R.id.gain_btn_mute_3,R.id.gain_btn_mute_4,R.id.gain_btn_mute_5,R.id.gain_btn_mute_6,R.id.gain_btn_mute_7,R.id.gain_btn_mute_8})
    ImageButton[] mChMuteButtons;

    //@BindView(R.id.pbx_gain_tv_total_vol)
    TextView txtTotalVol;
    /*//加减总音量
    @BindView(R.id.ibtn_total_plus)
    ImageButton mBtnPlus;
    @BindView(R.id.ibtn_total_sub)
    ImageButton mBtnSub;*/

    private PbxCircleRadioSeekBar pbx_gain_seekbar_ch1,pbx_gain_seekbar_ch2,pbx_gain_seekbar_ch3,pbx_gain_seekbar_ch4,pbx_gain_seekbar_ch5,pbx_gain_seekbar_ch6,pbx_gain_seekbar_ch7,pbx_gain_seekbar_ch8;
    //@BindViews({R.id.pbx_gain_seekbar_ch1,R.id.pbx_gain_seekbar_ch2,R.id.pbx_gain_seekbar_ch3,R.id.pbx_gain_seekbar_ch4,R.id.pbx_gain_seekbar_ch5,R.id.pbx_gain_seekbar_ch6,R.id.pbx_gain_seekbar_ch7,R.id.pbx_gain_seekbar_ch8})
    List<PbxCircleRadioSeekBar> mChVolSeekBars;

    private long mLastChangedTs;
    @Override
    protected int getResourceId() {
        return R.layout.fragment_gain;
    }
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews();

        YzDebug.d("Yang","onViewCreated:"+ sbTotalVol);
        sbTotalVol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                YzDebug.d("Yang","onProgressChanged:"+ progress,new Throwable());
                progress = progress/10;
                int db = progress -Constants.MAX_VOL;
                if (db == -Constants.MAX_VOL){
                    txtTotalVol.setText("Off");
                }else {
                    txtTotalVol.setText(db+"dB");
                }
                if (!updateOk) return;
                if (System.currentTimeMillis() - mLastChangedTs > Constants.SEEK_BAR_DELAY) {
                    mLastChangedTs = System.currentTimeMillis();
                    ADVANCE_SETTINGS.sendTotalVolCmd(progress, mCbxMute.isSelected());
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) { }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //  seekBar.setProgress(progress);
                //txtTotalVol.setText(String.valueOf(-DspSettings.MAX_VOL + seekBar.getProgress()) + "dB");// - 20
                //DspSettings.ADVANCE_SETTINGS.sendTotalVolCmd(seekBar.getProgress(), mCbxMute.isChecked());
                ADVANCE_SETTINGS.sendTotalVolCmd(seekBar.getProgress()/TOTAL_SCALE, mCbxMute.isSelected());
            }
        });
        mCbxMute.setOnClickListener(v->{
            boolean isSelect = !v.isSelected();
            v.setSelected(isSelect);
            enabledTotalVol(!isSelect);
            if (!updateOk) return;
            ADVANCE_SETTINGS.sendTotalVolCmd(sbTotalVol.getProgress()/TOTAL_SCALE, isSelect);
        });
        for (PbxCircleRadioSeekBar seekBar : mChVolSeekBars) {
            seekBar.setOnCircleSeekBarListener(mChVolListener);
            seekBar.setOnCircleSeekBarFunListener(mOnCircleSeekBarFunListener);
        }

    }


    private void initViews(){
        gain_btn_linked_1 = findViewById(R.id.gain_btn_linked_1);
        gain_btn_linked_2 = findViewById(R.id.gain_btn_linked_2);
        gain_btn_linked_3 = findViewById(R.id.gain_btn_linked_3);
        gain_btn_linked_4 = findViewById(R.id.gain_btn_linked_4);
        gain_btn_linked_5 = findViewById(R.id.gain_btn_linked_5);
        gain_btn_linked_6 = findViewById(R.id.gain_btn_linked_6);
        gain_btn_linked_7 = findViewById(R.id.gain_btn_linked_7);
        gain_btn_linked_8 = findViewById(R.id.gain_btn_linked_8);
        mIvLinks = new ImageButton[]{gain_btn_linked_1,gain_btn_linked_2,gain_btn_linked_3,gain_btn_linked_4,gain_btn_linked_5,gain_btn_linked_6,gain_btn_linked_7,gain_btn_linked_8};

        gain_btn_degress_1 = findViewById(R.id.gain_btn_degress_1);
        gain_btn_degress_2 = findViewById(R.id.gain_btn_degress_2);
        gain_btn_degress_3 = findViewById(R.id.gain_btn_degress_3);
        gain_btn_degress_4 = findViewById(R.id.gain_btn_degress_4);
        gain_btn_degress_5 = findViewById(R.id.gain_btn_degress_5);
        gain_btn_degress_6 = findViewById(R.id.gain_btn_degress_6);
        gain_btn_degress_7 = findViewById(R.id.gain_btn_degress_7);
        gain_btn_degress_8 = findViewById(R.id.gain_btn_degress_8);

        mChDegress = new ImageButton[]{gain_btn_degress_1,gain_btn_degress_2,gain_btn_degress_3,gain_btn_degress_4,gain_btn_degress_5,gain_btn_degress_6,gain_btn_degress_7,gain_btn_degress_8};

        for(ImageButton ig : mChDegress){
            ig.setOnClickListener(onChDegressClick);
        }

        sbTotalVol = findViewById(R.id.gain_seekbar_total_vol);
        mCbxMute = findViewById(R.id.pbx_gain_btn_total_mute);

        gain_btn_mute_1 = findViewById(R.id.gain_btn_mute_1);
        gain_btn_mute_2 = findViewById(R.id.gain_btn_mute_2);
        gain_btn_mute_3 = findViewById(R.id.gain_btn_mute_3);
        gain_btn_mute_4 = findViewById(R.id.gain_btn_mute_4);
        gain_btn_mute_5 = findViewById(R.id.gain_btn_mute_5);
        gain_btn_mute_6 = findViewById(R.id.gain_btn_mute_6);
        gain_btn_mute_7 = findViewById(R.id.gain_btn_mute_7);
        gain_btn_mute_8 = findViewById(R.id.gain_btn_mute_8);
        mChMuteButtons = new ImageButton[]{gain_btn_mute_1,gain_btn_mute_2,gain_btn_mute_3,gain_btn_mute_4,gain_btn_mute_5,gain_btn_mute_6,gain_btn_mute_7,gain_btn_mute_8};

        for(ImageButton mcIg : mChMuteButtons){
            mcIg.setOnClickListener(onChMuteClick);
        }


        txtTotalVol = findViewById(R.id.pbx_gain_tv_total_vol);
        pbx_gain_seekbar_ch1 = findViewById(R.id.pbx_gain_seekbar_ch1);
        pbx_gain_seekbar_ch2 = findViewById(R.id.pbx_gain_seekbar_ch2);
        pbx_gain_seekbar_ch3 = findViewById(R.id.pbx_gain_seekbar_ch3);
        pbx_gain_seekbar_ch4 = findViewById(R.id.pbx_gain_seekbar_ch4);
        pbx_gain_seekbar_ch5 = findViewById(R.id.pbx_gain_seekbar_ch5);
        pbx_gain_seekbar_ch6 = findViewById(R.id.pbx_gain_seekbar_ch6);
        pbx_gain_seekbar_ch7 = findViewById(R.id.pbx_gain_seekbar_ch7);
        pbx_gain_seekbar_ch8 = findViewById(R.id.pbx_gain_seekbar_ch8);

        mChVolSeekBars =new ArrayList<>();
        mChVolSeekBars.add(pbx_gain_seekbar_ch1);
        mChVolSeekBars.add(pbx_gain_seekbar_ch2);
        mChVolSeekBars.add(pbx_gain_seekbar_ch3);
        mChVolSeekBars.add(pbx_gain_seekbar_ch4);
        mChVolSeekBars.add(pbx_gain_seekbar_ch5);
        mChVolSeekBars.add(pbx_gain_seekbar_ch6);
        mChVolSeekBars.add(pbx_gain_seekbar_ch7);
        mChVolSeekBars.add(pbx_gain_seekbar_ch8);
    }


    private void enabledTotalVol(boolean enabled) {
//        YzDebug.d("Yang", "enabledTotalVol:"+ enabled,new Throwable());
        sbTotalVol.setEnabled(enabled);
        sbTotalVol.setAlpha(enabled?1f:DIENABLED_ALPHA);
        txtTotalVol.setEnabled(enabled);
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            ViewUtil.initChannelNames(mChVolSeekBars);
            updateData();
        } catch (Exception ex) {
            YzDebug.d("onResume", ex);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        DataUtil.saveAdvanceSettingsToDb();
        updateOk = false;
    }

    @Override
    public void onRefreshFragment(int cmd) {
        switch (cmd) {
            case CMD_SELECTED:
                updateData();
                break;
        }
    }

    private void syncLinkedChannel(int index) {
        if (index == -1) return;
        List<LevelChannel> levelChannels = ADVANCE_SETTINGS.getChannel();
        LevelChannel linkedChannel = levelChannels.get(index);
        PbxCircleRadioSeekBar seekBar = null;
        for (int i = 0; i < levelChannels.size(); i++) {
            LevelChannel levelChannel = levelChannels.get(i);
            seekBar = mChVolSeekBars.get(i);
            if (levelChannel.getLinked() == 1 && i != index) {
                levelChannel.setDegree(linkedChannel.getDegree());
                levelChannel.setMute(linkedChannel.getMute());
                levelChannel.setVal(linkedChannel.getVal());
                seekBar.setProgress(linkedChannel.getVal());


//                mEqChannel[i].setValue(levelChannel.getVal(), levelChannel.getMute() == 1, levelChannel.getDegree(), levelChannel.isChecked());
            }
            mChDegress[i].setSelected(levelChannel.getDegree() == 1);
            mChMuteButtons[i].setSelected(levelChannel.getMute() == 1);
            YzDebug.d("syncLinkedChannel getLinked:" +levelChannel.getLinked() );
            seekBar.setChecked(levelChannel.getLinked() == 1);
        }
    }

    boolean isUpdated = false, updateOk = false;
    private final int TOTAL_SCALE = 10;
    private void updateData() {

        updateOk = false;
        isUpdated = true;
        List<LevelChannel> channels = ADVANCE_SETTINGS.getChannel();
        try {
            for (int i = 0; i < channels.size(); i++) {
                LevelChannel channel = channels.get(i);
                mIvLinks[i].setTag(i);
                mIvLinks[i].setSelected(channel.getLinked() == 1);
                mIvLinks[i].setOnClickListener(v->{
                    boolean isSelected = !v.isSelected();
                    v.setSelected(isSelected);
                    int index = (int) v.getTag();
                    channel.setLinked(isSelected ? 1 : 0);

                    //LINKED选中后，对应通道也跟着选中，且只能通过LINKED取消；LINKED取消后，通道跟着取消选中
                    if (isSelected) {
                        int baseIndex = ADVANCE_SETTINGS.getBaseIndex();
                        if (baseIndex != -1) {
                            syncLinkedChannel(baseIndex);
                        }
                    }else{
                        mChVolSeekBars.get(index).setChecked(false);
                    }

                });
                mChMuteButtons[i].setSelected(channel.getMute() == 1);
                mChDegress[i].setSelected(channel.getDegree() == 1);
                //2023年8月1日 00:43:38
                mChVolSeekBars.get(i).setProgress(channel.getVal());

            }

        } catch (Exception ex) {
            YzDebug.d("updateData", ex);
        }


        //总音量
        sbTotalVol.setMax(Constants.MAX_VOL*TOTAL_SCALE);
        txtTotalVol.setText((-Constants.MAX_VOL + ADVANCE_SETTINGS.getTotalVol()) + "dB"); //
        sbTotalVol.setProgress(ADVANCE_SETTINGS.getTotalVol()*TOTAL_SCALE);
        mCbxMute.setSelected(ADVANCE_SETTINGS.getMute() == 1);

        isUpdated = false;
        mCbxMute.postDelayed(() -> updateOk = true, 200);

    }



    private final PbxCircleSeekBar.OnCircleSeekBarFunListener mOnCircleSeekBarFunListener = new PbxCircleSeekBar.OnCircleSeekBarFunListener() {
        @Override
        public void onFunClick(PbxCircleSeekBar bar, PbxCircleSeekBar.FunId id) {
            YzDebug.d("onFunClick: "+ id);
            int index = bar.getIndex();
            switch (id){
                case FUN_ID_SUB:
                    int val = ADVANCE_SETTINGS.getChannelByIndex(index).getVal();
                    if (val > 0)
                        val--;
                    changeChannelVol(index, val, true);
                    break;
                case FUN_ID_ADD:
                    val = ADVANCE_SETTINGS.getChannelByIndex(index).getVal();
                    if (val < Constants.MAX_VOL)
                        val++;
                    changeChannelVol(index, val, true);
                    break;
                case FUN_ID_TITLE:
                    bar.setSelected(!bar.isSelected());
                    break;
            }
        }
    };
    private void changeChannelVol(int index, int vol, boolean sendCmd){
        YzDebug.d("changeChannelVol index:"+ index +"  vol:"+ vol );
        LevelChannel ch = ADVANCE_SETTINGS.getChannel().get(index);
        ch.setVal(vol);
        if (ch.getLinked() == 1) {
            List<LevelChannel> levelChannels = ADVANCE_SETTINGS.getChannel();
            for (int i = 0, size = levelChannels.size(); i < size; i++) {
                LevelChannel channel = levelChannels.get(i);
                if (channel.getLinked() == 1 && channel != ch) {
                    channel.setVal(ch.getVal());
                    if (sendCmd) {
                        channel.sendVolume();
                    }
                }
                mChVolSeekBars.get(i).setProgress(channel.getVal());
            }
        }else{
            mChVolSeekBars.get(index).setProgress(ch.getVal());
        }
        if (sendCmd) {
            ch.sendVolume();
        }
    }
    private final PbxCircleSeekBar.OnCircleSeekBarListener mChVolListener = new PbxCircleSeekBar.OnCircleSeekBarListener() {
        private long mLastSendCmdTime;
        @Override
        public void onProgressChange(PbxCircleSeekBar seekBar, int progress, int action) {
            if (!updateOk) return;
            boolean sendCmd = false;
            long now = SystemClock.elapsedRealtime();
            if(action == MotionEvent.ACTION_UP || (now - mLastSendCmdTime) > 250){
                mLastSendCmdTime = now;
                sendCmd = true;
            }
            changeChannelVol(seekBar.getIndex(), progress, sendCmd);
        }
    };


    private View.OnClickListener onChDegressClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            boolean selected = !view.isSelected();
            view.setSelected(selected);
            int index = StringUtils.objectStringToInt(view.getTag(), -1);
            if (index == -1)return;
            LevelChannel ch = ADVANCE_SETTINGS.getChannel().get(index);
            ch.setDegree(selected ? 1 : 0);
            ch.sendDegree();
            if (ch.getLinked() == 1) {
                List<LevelChannel> levelChannels = ADVANCE_SETTINGS.getChannel();
                for (int i = 0; i < levelChannels.size(); i++) {
                    LevelChannel channel = levelChannels.get(i);
                    if (channel.getLinked() == 1 && channel != ch) {
                        channel.setDegree(ch.getDegree());
                        mChDegress[i].setSelected(selected);
//                    mEqChannel[i].setDegree(ch.getDegree(), false);
                        channel.sendDegree();
                    }
                }
            }
        }
    };

//    @OnClick({R.id.gain_btn_degress_1,R.id.gain_btn_degress_2,R.id.gain_btn_degress_3,R.id.gain_btn_degress_4,R.id.gain_btn_degress_5,R.id.gain_btn_degress_6,R.id.gain_btn_degress_7,R.id.gain_btn_degress_8})
//    public void onChDegressClick(View view){
//        boolean selected = !view.isSelected();
//        view.setSelected(selected);
//        int index = StringUtils.objectStringToInt(view.getTag(), -1);
//        if (index == -1)return;
//        LevelChannel ch = ADVANCE_SETTINGS.getChannel().get(index);
//        ch.setDegree(selected ? 1 : 0);
//        ch.sendDegree();
//        if (ch.getLinked() == 1) {
//            List<LevelChannel> levelChannels = ADVANCE_SETTINGS.getChannel();
//            for (int i = 0; i < levelChannels.size(); i++) {
//                LevelChannel channel = levelChannels.get(i);
//                if (channel.getLinked() == 1 && channel != ch) {
//                    channel.setDegree(ch.getDegree());
//                    mChDegress[i].setSelected(selected);
////                    mEqChannel[i].setDegree(ch.getDegree(), false);
//                    channel.sendDegree();
//                }
//            }
//        }
//
//    }



    private View.OnClickListener onChMuteClick  = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            boolean selected = !view.isSelected();
            view.setSelected(selected);
            int index = StringUtils.objectStringToInt(view.getTag(), -1);
            if (index == -1)return;
            LevelChannel ch = ADVANCE_SETTINGS.getChannel().get(index);
            ch.setMute(selected ? 1 : 0);
            ch.sendVolume();
            if (ch.getLinked() == 1) {
                List<LevelChannel> levelChannels = ADVANCE_SETTINGS.getChannel();
                for (int i = 0; i < levelChannels.size(); i++) {
                    LevelChannel channel = levelChannels.get(i);
                    if (channel.getLinked() == 1 && i != index) {
                        channel.setMute(ch.getMute());
                        mChMuteButtons[i].setSelected(selected);
                        channel.sendVolume();
                    }
                }
            }
        }
    };

//    @OnClick({R.id.gain_btn_mute_1,R.id.gain_btn_mute_2,R.id.gain_btn_mute_3,R.id.gain_btn_mute_4,R.id.gain_btn_mute_5,R.id.gain_btn_mute_6,R.id.gain_btn_mute_7,R.id.gain_btn_mute_8})
//    public void onChMuteClick(View view){
//        boolean selected = !view.isSelected();
//        view.setSelected(selected);
//        int index = StringUtils.objectStringToInt(view.getTag(), -1);
//        if (index == -1)return;
//        LevelChannel ch = ADVANCE_SETTINGS.getChannel().get(index);
//        ch.setMute(selected ? 1 : 0);
//        ch.sendVolume();
//        if (ch.getLinked() == 1) {
//            List<LevelChannel> levelChannels = ADVANCE_SETTINGS.getChannel();
//            for (int i = 0; i < levelChannels.size(); i++) {
//                LevelChannel channel = levelChannels.get(i);
//                if (channel.getLinked() == 1 && i != index) {
//                    channel.setMute(ch.getMute());
//                    mChMuteButtons[i].setSelected(selected);
//                    channel.sendVolume();
//                }
//            }
//        }
//    }

}
